package com.yb.livewykt.vm

import android.app.Application
import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.google.gson.JsonObject
import com.yb.livewykt.bean.Me
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.LoginInfo
import com.yb.livewykt.util.*

class LoginViewModel(application: Application) : BaseViewModel(application) {

    val password = MutableLiveData<String>()
    val phone = MutableLiveData<String>()
    val myData = MutableLiveData<Me>()
    val isLoginSuccess = MutableLiveData<Boolean>()

    init {
        phone.value = SaveUserData.get().phone
        password.value = SaveUserData.get().password
        if (!phone.value.isNullOrEmpty() && !password.value.isNullOrEmpty()){
            login()
        }
    }

    fun login(){
        if (TextUtils.isEmpty(phone.value)){
            PHONE_NULL.showToast()
            return
        }
        if (TextUtils.isEmpty(password.value)){
            PASSWORD_NULL.showToast()
            return
        }

        val hashMap = HashMap<String,Any>()
        hashMap["mobile"] = phone.value!!
        hashMap["password"] = password.value!!
        hashMap["type"] = 1
        SaveUserData.get().phone = phone.value!!
        SaveUserData.get().password = password.value!!
        launch ({userApi.login(hashMap)} , myData)
    }

    fun wyLogin(accid:String,imToken:String){
        val info = LoginInfo(
            accid,
            imToken,
            IM_APP_KEY
        )
        val loginInfoRequestCallback: RequestCallback<LoginInfo> =
            object : RequestCallback<LoginInfo> {
                override fun onSuccess(param: LoginInfo) {
                    Log.d(TAG, "onSuccess: ${param.account}")
                    isLoginSuccess.value = true
                    loginStatue(true)
                }

                override fun onFailed(code: Int) {
                    Log.d(TAG, "onFailed: $code")
                    isLoginSuccess.value = false
                    loginStatue(false)
                }

                override fun onException(exception: Throwable) {
                    loginStatue(false)
                    Log.d(TAG, "onException: " + exception.message)
                }
            }
        NIMClient.getService(AuthService::class.java).login(info)
            .setCallback(loginInfoRequestCallback)
    }
}